package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.Demo;
import com.tanhua.model.mongo.UserTest;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.CriteriaDefinition;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
import java.util.stream.Collectors;

@DubboService
public class DemoApiImpl implements DemoApi {
    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public List<Demo> gettestSoul(Long userId) {
        UserTest userId1 = mongoTemplate.findOne(Query.query(Criteria.where("userId").is(userId)), UserTest.class);
        if (userId1==null){
            CriteriaDefinition criteria=Criteria.where("name").is("初级灵魂题");
            List<Demo> demos = mongoTemplate.find(Query.query(criteria), Demo.class);
            List<String> collect = demos.stream().map(Demo::getId).collect(Collectors.toList());
            userId1 = new UserTest(userId,collect.toString());
            mongoTemplate.save(userId1);
        }
        String[] split = StringUtils.strip(userId1.getTestId(), "[]").split(",");
        CriteriaDefinition criteria=new Criteria();
        List<Demo> demos = mongoTemplate.find(Query.query(criteria), Demo.class);
        demos.forEach(c->{
            for (String s : split) {
                if (c.getId().equals(s)){
                    c.setIsLock(0);
                }
            }
        });

        return demos;
    }
}
